package MovieGuessingGame.login;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.SocketTimeoutException;

import javax.swing.JFrame;

import MovieGuessingGame.player.GameJFrame;
import MovieGuessingGame.clientutil.ClientSSL;

public class LoginController {
	
	private String servername = null;
	private ClientSSL loginConnect = null;
	private ClientSSL gameConnect = null;
	LoginJPanel login = null;
	JFrame frame = null;
	
	
	public LoginController(String serverhost){
		servername = serverhost;
	}
	
	private void init()
	{
		loginConnect = new ClientSSL();
		loginConnect.clientConnect(servername, 9999);
		

	}
	
	void displayPanel()
	{
		login = new LoginJPanel();
		frame = new JFrame("MovieGuessingGame");
		
		login.setOpaque(true);
		frame.setContentPane(login);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		login.btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String value = new String( login.passwordField.getPassword() );
				setUpConnectionToServer(login.getUserName(),value);
				
			}
		});
		
		login.btnStartButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				login.setStartButtonText("Waiting...");
				frame.repaint();
				String value = (String) login.playerBox.getSelectedItem();
				startGamePlay(value);
			}
		});
		
		frame.addWindowListener( 
			    new WindowAdapter() { 
			        public void windowClosing(WindowEvent e) { 
			        	if (loginConnect != null ){
			        		loginConnect.closeSocket();
			        	}
			        	if (gameConnect != null ){
			        		gameConnect.closeSocket();
			        	}
			            System.exit(0); 
			        } 
			    } 
			);
		
		frame.setSize(500, 400);
		login.setVisible(true);
		frame.setVisible(true);
		
	}
	
	private void setUpConnectionToServer(String userName,String password)
	{
		try {
			loginConnect.sendCreds(userName,password);
			System.out.println("sent creds");
			
			int outcome = loginConnect.recvHash();
			System.out.println("got outcome: "+outcome);
			if (outcome == -1)
			{
				// Displays message, and forces restart if you didn't log in ok
				login.setMessageFieldText(loginConnect.getMessage());
				login.btnNewButton.setEnabled(false);

				frame.setVisible(false);
				frame.setVisible(true);
				frame.setSize(500, 400);
				login.setVisible(true);
				frame.repaint();
				
			}
			else{
				System.out.println("logged in ok");
				
				gameConnect = new ClientSSL();
				gameConnect.clientConnect(servername, 8903);
				
				gameConnect.setHash(loginConnect.getHashValue());
				gameConnect.sendHash();
				
				String to_recv = gameConnect.clientReceive();
				System.out.println("DEBUG: GOT playerlist: "+to_recv);
				String[] players = to_recv.split(",");
				
				
				login.playerBox.addItem("WaitForOpponent");
				for( int i =0; i<players.length; i++ )
					login.playerBox.addItem(players[i]);
				
				
				login.playerBox.setEnabled(true);
				login.btnStartButton.setEnabled(true);
				
				frame.repaint();
				
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		
	}
	
	private void startGamePlay(String value) {
		
		
		System.out.println("DEBUG: startGamePLay got value: "+value );
		try {
			
			// Send our opponent preference
			gameConnect.clientSend(value);
			
			
			// Now wait for the game to start... but set a timeout of 10 sec
			gameConnect.setTimeout(60 * 1000);
			String result = gameConnect.clientReceive();
			System.out.println("Got start token: "+result);
			gameConnect.setTimeout(0);
		
			
		} catch (SocketTimeoutException e2) {
			login.setMessageFieldText("Timeout waiting for Opponent!");
			login.btnNewButton.setEnabled(false);
			login.btnStartButton.setEnabled(false);
			return;
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return;
		} 
		
		try {
			new Thread( new GameJFrame(gameConnect) ).start();
			frame.dispose();
			
		} catch (Exception e) {
			System.out.println("exception from GameJFrame()");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LoginController loginControl = new LoginController("localhost");
		loginControl.init();
		loginControl.displayPanel();
	}

}
